<?php

class MainRouter extends CBaseUrlRule {

    public $connectionID = 'db';

    public function createUrl($manager, $route, $params, $ampersand) {
        $arrayUrl = explode('/', $route);
        if (isset($arrayUrl[2]) && $arrayUrl[2] == 'captcha')
            return 'main/ajax/captcha' . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
        if (isset($arrayUrl[1]) && $arrayUrl[1] == 'ajax')
            return $route . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
        return Yii::app()->request->pathInfo . (!empty($params) ? '?' : '') . http_build_query($params, '', '&');
    }

    public function parseUrl($manager, $request, $pathInfo, $rawPathInfo) {

        $qa = FALSE;

        $arrayUrl = explode('/', $pathInfo);

        if ($pathInfo == 'for-suppliers') {
            Controller::$pageData = [
                'pageTitle' => 'For suppliers',
                'pageType' => 'page',
                'pageUrl' => 'for-suppliers',
                'pageId' => 0,
                'pageLanguage' => 'en'
            ];
            return 'main/main/supplier';
        }

        if ($pathInfo == 'dlya-postavshikov') {
            Controller::$pageData = [
                'pageTitle' => 'Для поставщиков',
                'pageType' => 'page',
                'pageUrl' => 'dlya-postavshikov',
                'pageId' => 0,
                'pageLanguage' => 'ru'
            ];
            return 'main/main/supplier';
        }

        if (strtoupper($arrayUrl[0]) == "IMAGE" && strtoupper($arrayUrl[1]) == "RESIZE") {
            list($x, $y) = explode("x", $arrayUrl[2]);

            Controller::$pageData['_image'] = [
                'width' => $x,
                'height' => $y,
                'image_dir' => str_replace(end($arrayUrl), "", str_replace("image/resize/" . $arrayUrl[2], "", $pathInfo)),
                'image_file' => end($arrayUrl)
            ];

            return 'main/image/resize';
        }

        if ($pathInfo == 'qa/ask') {
            Controller::$pageData = [
                'pageTitle' => 'Задать вопрос',
                'pageType' => 'page',
                'pageUrl' => 'qa/ask',
                'pageId' => 0
            ];
            return '/main/qa/ask';
        }

        if ($pathInfo == 'password/restore')
            return '/main/password/restore';

        if ($pathInfo == 'logout')
            return '/main/ajax/logout';

        if ($pathInfo == 'login')
            return '/main/ajax/login';

        if (isset($arrayUrl[1]) && $arrayUrl[1] == 'ajax')
            return $pathInfo;

        if (strtoupper($arrayUrl[0]) == 'QA')
            $qa = TRUE;

        if (!$qa) {
//            $redirects = include Yii::app()->basePath . '/redirects/redirects.php';
//            if (isset($redirects[$pathInfo]))     
//            {
//                Yii::app()->getRequest()->redirect('/'.$redirects[$pathInfo], true, 301);                    
//            }

            $path = $this->getUrl(!empty($pathInfo) ? $pathInfo : '/' );
            $hasParent = true;

            $result['pageParent'] = $path['pageParent'];

            while ($hasParent) {
                if ($result['pageParent'] != 0) {
                    $result = $this->getUrl('', $result['pageParent']);

                    $path['_parents'][$result['pageType']] = [
                        'pageId' => $result['pageId'],
                        'pageTitle' => pg_escape_string($result['pageTitle']),
                        'pageUrl' => $result['pageUrl']
                    ];
                } else
                    $hasParent = false;
            }
            if (!$path)
                return '/main/main/error';
            /*  is model was not found
             *             if (!$path) {
              $redirects = include Yii::app()->basePath . '/redirects/redirects.php';
              if (isset($redirects[$pathInfo]))
              Yii::app()->getRequest()->redirect('/'.$redirects[$pathInfo], true, 301);
              else
              return '/main/main/error';//
              }
             */
            Controller::$pageData = $path;
            return '/main/' . $path['pageAction'];
        } elseif ($qa) {
            if ($pathInfo == 'qa/parse')
                return '/main/qa/parse';
            if ($pathInfo == 'qa') {
                Controller::$pageData = [
                    'pageTitle' => 'Вопросы и Ответы',
                    'pageType' => 'faq',
                    'pageUrl' => 'qa'
                ];

                return '/main/qa';
            }
            $short = str_replace('qa/', '', $pathInfo);
            $array = explode('/', $short);
            if (count($array) >= 4) {
                $path = $this->getFaq($pathInfo);
                if (!$path)
                    return '/main/main/error';

                //$path['pageTitle'] = 'Вопросы и Ответы';

                Controller::$pageData = $path;
                return '/main/qa/view';
            } else {

                foreach (Yii::app()->params['categories'] as $key => $value) {
                    $arr1[] = $value['faqUrl'];
                    $arr2[] = $value['pageUrl'];
                }

                $pathInfo = str_replace($arr1, $arr2, $pathInfo);
                $short = str_replace('qa/', '', $pathInfo);

                if ($array[0] == 'mp3-pleeery' || $array[0] == 'elektronnye-knigi' || $array[0] == 'remont-kompyuterov')
                    return '/main/main/error';
                //echo $short;exit;
                $path = $this->getUrl($short);
                if (!$path)
                    return '/main/main/error';

                $hasParent = true;

                $result['pageParent'] = $path['pageParent'];

                while ($hasParent) {
                    if ($result['pageParent'] != 0) {
                        $result = $this->getUrl('', $result['pageParent']);

                        $path['_parents'][$result['pageType']] = [
                            'pageId' => $result['pageId'],
                            'pageTitle' => $result['pageTitle'],
                            'pageUrl' => $result['pageUrl']
                        ];
                    } else
                        $hasParent = false;
                }
                $path['pageFaqType'] = $path['pageType'];
                $path['pageType'] = 'faq';
                Controller::$pageData = $path;
                return '/main/qa';
            }
        }
    }

    public function getUrl($url, $id = false) {
        if (!$id) {
            return Yii::app()->db->getCommandBuilder()->createSqlCommand("SELECT * FROM {{pages}} p LEFT JOIN {{metas}} m ON p.\"pageId\" = m.\"itemId\" AND m.\"itemType\"='page' WHERE p.\"pageUrl\" = '{$url}' AND p.\"pageActive\" = 1")->queryRow();
        } else {
            return Yii::app()->db->getCommandBuilder()->createSqlCommand("SELECT * FROM {{pages}} p LEFT JOIN {{metas}} m ON p.\"pageId\" = m.\"itemId\" AND m.\"itemType\"='page' WHERE p.\"pageId\" = '{$id}' AND p.\"pageActive\" = 1")->queryRow();
        }
    }

    public function getFaq($url) {
        $faq = Yii::app()->db->getCommandBuilder()->createSqlCommand("SELECT * FROM {{faq}} WHERE \"faqUrl\" = '$url' AND \"faqGlobalType\" = 'qa' AND \"faqStatus\" = '1'")->queryRow();
        if ($faq) {
            $model = Yii::app()->db->getCommandBuilder()->createSqlCommand("SELECT \"pageId\", \"pageParent\", \"pageTitle\", \"pageUrl\" FROM {{pages}} p WHERE p.\"pageId\" = {$faq['faqModelId']} AND p.\"pageType\"='model' AND p.\"pageActive\" = 1")->queryRow();
            if ($model) {
                $brand = Yii::app()->db->getCommandBuilder()->createSqlCommand("SELECT \"pageId\", \"pageParent\", \"pageTitle\", \"pageUrl\" FROM {{pages}} p WHERE p.\"pageId\" = {$model['pageParent']} AND p.\"pageType\"='brand' AND p.\"pageActive\" = 1")->queryRow();
                if ($brand) {
                    foreach (Yii::app()->params['categories'] as $cat) {
                        if ($cat['pageId'] == $brand['pageParent']) {
                            $faq['_parents'] = [
                                'model' => [
                                    'pageId' => $model['pageId'],
                                    'pageTitle' => $model['pageTitle'],
                                    'pageUrl' => $model['pageUrl']
                                ],
                                'brand' => [
                                    'pageId' => $brand['pageId'],
                                    'pageTitle' => $brand['pageTitle'],
                                    'pageUrl' => $brand['pageUrl']
                                ],
                                'category' => [
                                    'pageId' => $cat['pageId'],
                                    'pageTitle' => $cat['pageTitle'],
                                    'pageUrl' => $cat['pageUrl']
                                ],
                                'faq' => [
                                    'pageId' => 0,
                                    'pageTitle' => 'Вопросы и ответы',
                                    'pageUrl' => 'qa',
                                ],
                            ];
                            $faq['pageUrl'] = $faq['faqUrl'];
                            $faq['pageType'] = 'faq';
                            $faq['pageTitle'] = $faq['faqTitle'];
                            return $faq;
                        }
                    }
                }
            }
        }
        return false;
    }

}
